<?php

namespace app\api\controller\v2;

use app\admin\model\cms\AlbumModel;
use app\admin\model\cms\Comment;
use app\admin\model\cms\OrderModel;
use app\admin\model\cms\Platepost;
use app\admin\model\Investment;
use app\admin\model\Score as ScoreModel;

use app\admin\model\User;
use app\common\controller\Api;
use app\common\model\Attachment;
use app\common\model\UserFavorite;
use app\common\model\UserLike;
use fast\Arr;
use think\Db;
use think\Exception;

/**
 * 日历控制器
 */
class CalendarTag extends Api
{

    //无需鉴权的方法,但需要登录
    protected $noNeedRight = '*';

    //获取日历列表(指定天数用户得到积分的文章内容列表)
    public function calendarTagList()
    {
        $year_month = $this->request->param('year_month','');//日期|格式:年月日 如:2023-11-05
        $page = $this->request->param('page',1);
        $limit = $this->request->param('limit',10);
        if (!isset($year_month) || strlen($year_month) != 10) {
            $this->error("日期参数错误！！");
        }

        $user = $this->auth->getUser();//用户信息

        $start_time = strtotime($year_month . ' 00:00:00');//开始时间
        $end_time = strtotime($year_month . ' 23:59:59');//结束时间


        $list = \app\admin\model\Score::where('user_id', $user['id'])
            ->where('seq_flag', 1)//变动方向:1=增加,2=减少
            ->whereIn('change_type',[2,3,4,5,6,7,8,9,11])
            ->whereBetween('change_time', [$start_time, $end_time])
            ->field('id,change_type,ref_sn,comments,table_name')
            ->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page])
            ->toArray();




        $plate_ids = [];
        $video_ids = [];
        $album_ids = [];
        $live_ids = [];
        $investment_ids = [];
        foreach($list['data'] as $v){
            switch ($v['table_name']){
                case 'plate_post':
                    $plate_ids[] = $v['ref_sn'];
                    break;
                case 'video':
                    $video_ids[] = $v['ref_sn'];
                    break;
                case 'album':
                    $album_ids[] = $v['ref_sn'];
                    break;
                case 'live':
                    $live_ids[] = $v['ref_sn'];
                    break;
                case 'investment':
                    $investment_ids[] = $v['ref_sn'];
                    break;
            }
        }


        $res =[
            'plateList' => $this->getPlatePostList($plate_ids,$user),//论坛
            'videoList' => $this->getVideotList($video_ids,$user),//视频
            'albumList' => $this->getAlbumList($album_ids,$user),//视频专辑
            'liveList' => $this->getLiveList($live_ids,$user),//直播
            'investmentList' => $this->getInvestmentList($investment_ids,$user),//数据库
        ];


        $this->success('',$res);
    }

    //获取论坛文章
    private function getPlatePostList(array $id_arr, $user)
    {
        if (!$id_arr) {
            return [];
        }

        //查询帖子列表
        $data = Platepost::whereIn('id', $id_arr)
            ->order('is_jing', 'desc')
            ->order('id', 'desc')
            ->select();
        if (!count($data)){
            return [];
        }

        $res = [];
        foreach($data as $v){
            //检测用户是否有权访问内容
            $v['is_member_expire'] = 0;//会员是否到期|0:否,1:是
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'plate_post', $v['id'], $v['plateid']);
            if ($hasMembershipExpiryRecord['code'] != 200) {
                $v['is_member_expire'] = 1;//会员是否到期|0:否,1:是
            }

            //得到当前文章的评论
            $commentData = Comment::where('pid', 0)->where('aid', $v['id'])
                ->where('type', 'bbs')
                ->with(['user', 'children'])
                ->limit(5)->select();

            $commentList = [];
            foreach ($commentData as $ck => $cv) {
                $commentList[$ck] = $cv->toArray();
                $commentList[$ck]['createtime'] = date('Y-m-d H:i:s', $commentList[$ck]['createtime']);
                if (!$cv['user']) {
                    //获取软删除用户
                    $cv['user'] = User::getSoftDeleteUser($cv['user_id']);
                }

                $commentList[$ck]['user'] = [
                    'id' => $cv['user']['id'] ?? '',
                    'username' => $cv['user']['nickname'] ?? '',
                    'avatar' => obsurl($cv['user']['avatar'] ?? ''),
                ];
                $commentList[$ck]['is_children'] = $cv['children'] ? 1 : 0;//是否存在子集|0:否,1:是
            }
            $is_mylike = UserLike::where('table_name', 'plate_post')
                ->where('user_id', $user['id'])
                ->where('object_id', $v['id'])
                ->find();
            $is_myfavorite = UserFavorite::where('table_name', 'plate_post')
                ->where('user_id', $user['id'])
                ->where('object_id', $v['id'])
                ->find();

            if (!$v['user']) {
                //获取软删除用户
                $v['user'] = User::getSoftDeleteUser($v['user_id']);
            }

            $avatar = '';
            if ($v['user']['avatar'] ?? '') {
                $avatar = obsurl($v['user']['avatar']);
            }
            if ($v['file']) {
                $v['file'] = obsurl($v['file']);
            }

            $file_img = [];
            foreach(explode(',', $v['file_img']) as $path){
                $file_img[] = obsurl($path);
            }
            $file_video = [];
            foreach(explode(',', $v['file_video']) as $path){
                $file_video[] = obsurl($path);
            }

            $file_audio = [];
            foreach(explode(',', $v['file_audio']) as $path){
                $file_audio[] = obsurl($path);
            }

            $file_data = [];
            if ($v['file_data']){
                $attachment = Attachment::whereIn('url',$v['file_data'])->select();
                foreach ($attachment as $av) {
                    $file_data[] = [
                        'filename'=>$av['filename'],
                        'url'=>obsurl($av['url'])
                    ];
                }
            }

            $content_arr = [
                'table_name' => 'plate_post',//点赞收藏用|内容以前所在表,不带前缀|news:新闻,plaza_post:广场,video:视频,plate_post:论坛
                'category_type' => 'plate',//查看详情用|类型|plaza:广场帖子,plate:论坛帖子,news:新闻,video:视频,live:直播,investment:投研日志
                'comment_type' => 'bbs',//发布评论用|news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播
                'id' => $v['id'],
                'post_title' => $v['postname'],//标题
                'post_content' => $v['postcontent'],//内容
                'membership_price' => $v['membership_price'],//会员价格|0:免费
                'user_id' => $v['user_id'],//用户id
                'avatar' => $avatar,//用户头像
                'username' => $v['user']['nickname'] ?? '',//昵称
                'thumbnail' => $v['file'],//图片链接
                'is_accessory' => ($v['accessory'] ? 1 : 0),//是否存在附件|0:否,1:是
                'is_top' => $v['top'],//是否置顶|0:否
                'is_jing' => $v['is_jing'],//是否加精|0:否
                'is_mylike' => $is_mylike ? 1 : 0,//是否喜欢|0:否
                'is_myfavorite' => $is_myfavorite ? 1 : 0,//是否收藏|0:否
                'recommended' => $v['is_jing'],//是否推荐|0:否
                'commentList' => $commentList,//顶级评论列表
                'create_time' => $v['creat_time'],//创建时间

                'post_like' => $v['post_like'],//点赞数量
                'post_favorites' => $v['post_favorites'] ?? 0,//收藏数量
                'comment_count' => $v['comment_count'],//评论数量
                'post_hits' => 0,//点击量
                'post_forward' => $v['post_forward'],//转发数量

                'is_author' => 0,//是否为作者|0:否,1:是
                'is_member_expire' => 0,//会员是否到期|0:否,1:是

                'file_img' => array_filter($file_img),//图片数组
                'file_img_num' => count(array_filter($file_img)),//图片数组
                'file_video' => array_filter($file_video),//视频数组
                'file_audio' => array_filter($file_audio),//音频数组
                'file_data' => array_filter($file_data),//文件数组
                'is_reprint'=>$this->is_reprint($v['postcontent']),//判断文章内容是否是转载 1:是,0:否
            ];

            if ($user['id'] == $v['user_id']) {
                $content_arr['is_author'] = 1;
            }
            $res[] = $content_arr;
        }
        return  $res;
    }

    //获取视频列表
    private function getVideotList(array $id_arr, $user)
    {
        if (!$id_arr) {
            return [];
        }
        $data = \app\admin\model\cms\Video::whereIn('id', $id_arr)
            ->with(['user'])
            ->order('is_top', 'desc')
            ->order('sort', 'desc')
            ->order('id', 'desc')
            ->select();

        $res = [];
        foreach ($data as $v) {
            //得到当前文章的评论
            $commentData = Comment::where('pid', 0)->where('aid', $v['id'])
                ->where('type', 'video')
                ->with(['user', 'children'])
                ->limit(5)->select();

            $commentList = [];
            foreach ($commentData as $ck => $cv) {
                $commentList[$ck] = $cv->toArray();
                $commentList[$ck]['createtime'] = date('Y-m-d H:i:s', $commentList[$ck]['createtime']);
                if (!$cv['user']) {
                    $cv['user'] = User::getSoftDeleteUser($cv['user_id']);
                }
                $commentList[$ck]['user'] = [
                    'id' => $cv['user']['id'],
                    'username' => $cv['user']['nickname'],
                    'avatar' => $cv['user']['avatar'],
                ];
                $commentList[$ck]['is_children'] = $cv['children'] ? 1 : 0;//是否存在子集|0:否,1:是
                $commentList[$ck]['is_author'] = 0;//是否为评论作者|1:是,0:否
                if ($commentList[$ck]['user']['id'] == $user['id']) {
                    $commentList[$ck]['is_author'] = 1;//是否为评论作者|1:是,0:否
                }
            }

            $is_mylike = UserLike::where('table_name', 'video')
                ->where('user_id', $user['id'])
                ->where('object_id', $v['id'])
                ->find();
            $is_myfavorite = UserFavorite::where('table_name', 'video')
                ->where('user_id', $user['id'])
                ->where('object_id', $v['id'])
                ->find();

            if ($v['image']) {
                if (substr($v['image'], 0, 1) === '/') {
                    $v['image'] = obsurl($v['image']);
                }
            }
            if ($v['video_path']) {
                if (substr($v['video_path'], 0, 1) === '/') {
                    $v['video_path'] = obsurl($v['video_path']);
                }
            }

            if (!$v['user']) {
                //获取软删除用户
                $v['user'] = User::getSoftDeleteUser($v['user_id']);
            }

            if ($v['user']['avatar'] ?? '') {
                $v['user']['avatar'] = obsurl($v['user']['avatar']);
            }


            //内容数组
            $content_arr = [
                'id' => $v['id'],
                'title' => $v['title'],//标题
                'description' => $v['description'],//描述
                'image' => $v['image'],//封面图片
                'video_path' => $v['video_path'],//视频链接
                'is_top' => $v['is_top'],//是否置顶|0:否
                'type' => $v['type'],//类型：1视频2音频
                'is_mylike' => $is_mylike ? 1 : 0,//是否喜欢|0:否
                'is_myfavorite' => $is_myfavorite ? 1 : 0,//是否收藏|0:否
                'user_id' => $v['user_id'],//用户id
                'thumbnail' => $v['user']['avatar'],//头像
                'username' => $v['user']['nickname'],//昵称
                'commentList' => $commentList,//顶级评论列表
                'create_time' => $v['create_time'],//创建时间

                'post_like' => $v['count_like'] ?? 0,//点赞数量
                'post_hits' => $v['count_view'] ?? 0,//点击量
                'post_favorites' => $v['count_favorite'] ?? 0,//收藏数量
                'comment_count' => $v['count_comment'],//评论数量
                'post_forward' => $v['count_forward'] ?? 0,//转发数量

                'membership_price' => $v['membership_price'],//会员价格|0:免费
                'is_member_expire' => 0,//会员是否到期|0:否,1:是
            ];

            //检测用户是否有权访问内容
            $v['is_member_expire'] = 0;//会员是否到期|0:否,1:是
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'video', $v['id'], $v['video_category_id']);
            if ($hasMembershipExpiryRecord['code'] != 200) {
                //没开内容会员
                $content_arr['is_member_expire'] = 1;//会员是否到期|0:否,1:是
                $content_arr['description'] = '';
                $content_arr['image'] = '';
                $content_arr['video_path'] = '';
            }
            $res[] = $content_arr;
        }
        return $res;
    }
    //获取专辑列表
    private function getAlbumList(array $id_arr, $user){
        if (!$id_arr) {
            return [];
        }
        //获取专辑
        $albumList_model = AlbumModel::where('table_name', 'video_category')
            ->whereIn('id', $id_arr)
            ->order('sort','desc')
            ->select();
        $album_count = count($albumList_model);
        $res = [];
        foreach ($albumList_model as $v) {
            //内容数组
            $content_arr = [
                'id' => $v['id'],//专辑id
                'name' => $v['name'],//专辑名称
                'introduction' => $v['introduction'],//介绍
                'cover_image' => obsurl($v['cover_image']),//封面图url
                'table_name' => $v['table_name'],//分类类型|数据源不加前缀的表名|video_category=视频
                'category_id' => $v['category_id'],//所属分类id数据源不加前缀的表中的id|专辑归属的分类id
                'membership_price' => $v['membership_price'],//会员价格(元)|默认0:免费
                'membership_duration' => $v['membership_duration'],//会员天数|默认0天
                'is_member_expire' => 0,//会员是否到期|0:否,1:是
                'quantity_sold' => OrderModel::where('table_name', 'album')->where('goods_id', $v['id'])->where('pay_status', 1)->count()//专辑购买数量
            ];

            //检测用户是否有权访问内容
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'album', $v['id'], $v['category_id']);
            if ($hasMembershipExpiryRecord['code'] != 200) {
                //没开内容会员
                $content_arr['is_member_expire'] = 1;//会员是否到期|0:否,1:是
            }
            $res[] = $content_arr;
        }
        return  $res;
    }

    //获取直播列表
    private function getLiveList(array $id_arr, $user){
        if (!$id_arr) {
            return [];
        }

        $data = \app\admin\model\cms\Live::
            whereIn('id',$id_arr)
            ->order('is_top', 'desc')
            ->order('id', 'dese')
            ->select();

        $res = [];
        foreach ($data as $v) {
            $comment_count = Comment::favTotal($v['id'], 'live');//点赞总数
            //内容数组
            if ($v['image']) {
                if (substr($v['image'], 0, 1) === '/') {
                    $v['image'] = obsurl($v['image']);
                }
            }
            $content_arr = [
                'id' => $v['id'],
                'title' => $v['title'],//标题
                'description' => $v['description'],//描述
                'image' => $v['image'],//封面图片
                'live_url' => $v['live_url'],//直播地址
                'live_time' => $v['live_time'],//直播时间
                'is_top' => $v['is_top'],//是否置顶|0:否
                'is_start_live' => $v['is_start_live'],//是否开始直播|0:否
                'create_time' => $v['create_time'],//创建时间
                'membership_price' => $v['membership_price'],//会员价格|0:免费
                'comment_count' => $comment_count,//评论数量
                'is_member_expire' => 0,//会员是否到期|0:否,1:是
            ];

            //检测用户是否有权访问内容
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'live', $v['id'], $v['live_category_id']);
            if ($hasMembershipExpiryRecord['code'] != 200) {
                //没开内容会员
                $content_arr['is_member_expire'] = 1;//会员是否到期|0:否,1:是
                $content_arr['description'] = '';
                $content_arr['image'] = '';
                $content_arr['live_url'] = '';
            }

            $res[] = $content_arr;
        }

        return $res;


    }

    //获取数据库列表
    private function getInvestmentList(array $id_arr, $user){
        if (!$id_arr) {
            return [];
        }

        $data = Investment::whereIn('id',$id_arr)
            ->order('content_time', 'desc')
            ->select();

        $arList = [];
        foreach ($data as $v) {
            //内容数组
            $content_arr = [
                'id' => $v['id'],
                'macro_content' => $v['macro_content'],//宏观面
                'policy_content' => $v['policy_content'],//政策面
                'fund_content' => $v['fund_content'],//资金面及预期
                'emotion_content' => $v['emotion_content'],//情绪面
                'expect_content' => $v['expect_content'],//市场预期/关注
                'news_content' => $v['news_content'],//市场新闻
                'content_time' => date('Y-m-d H:i:s', $v['content_time']),//时间
                'create_time' => date('Y-m-d H:i:s', $v['createtime']),//创建时间
                'is_member_expire' => 0,//会员是否到期|0:否,1:是
            ];

            //检测用户是否有权访问内容
            $hasMembershipExpiryRecord = $this->hasMembershipExpiryRecordArticles($user['id'], 'investment', $v['id'], $v['investment_category_id']);
            if ($hasMembershipExpiryRecord['code'] != 200) {
                //没开内容会员
                $content_arr['is_member_expire'] = 1;//会员是否到期|0:否,1:是
            }
            $arList[] = $content_arr;
        }

        return $arList;
    }

    //判断文章内容是否是转载 1:是,0:否
    private function is_reprint($content){
        $prefix = '【转载--';
        $is_reprint = strpos($content, $prefix) === 0;
        return $is_reprint ? 1:0;
    }

}
